import 'package:ati_package/core/utils/ati_assets.dart';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../views/image_preview_view.dart';

/// 简单的数据模型 —— 可根据后端真实数据调整
class Post {
  final String avatar;
  final String username;
  final String time;
  final String text;
  final List<String> images;
  final int likes;
  final int commentsCount;
  final List<String> comments;

  const Post({
    required this.avatar,
    required this.username,
    required this.time,
    required this.text,
    this.images = const [],
    this.likes = 0,
    this.commentsCount = 0,
    this.comments = const [],
  });
}

class PostCard1 extends StatefulWidget {
  final Post post;
  const PostCard1({super.key, required this.post});

  @override
  State<PostCard1> createState() => _PostCard1State();
}

class _PostCard1State extends State<PostCard1>
    with SingleTickerProviderStateMixin {
  bool commentsExpanded = false;
  bool loadingComments = false;
  bool liked = false;
  late List<String> displayComments;
  late AnimationController _likeController;
  late Animation<double> _scaleAnim;

  @override
  void initState() {
    super.initState();
    displayComments = widget.post.comments.take(2).toList();

    // ❤️ 初始化点赞动画控制器
    _likeController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 250),
    );

    _scaleAnim = Tween<double>(begin: 1.0, end: 1.4).animate(
      CurvedAnimation(parent: _likeController, curve: Curves.easeOutBack),
    );

    _likeController.value = 1.0;
  }

  @override
  void dispose() {
    _likeController.dispose();
    super.dispose();
  }

  Future<void> _expandComments() async {
    if (commentsExpanded) return;
    setState(() => loadingComments = true);
    await Future.delayed(const Duration(milliseconds: 700)); // 模拟请求
    setState(() {
      displayComments = widget.post.comments;
      commentsExpanded = true;
      loadingComments = false;
    });
  }

  void _openGallery(int index) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) =>
            ImagePreviewView(images: widget.post.images, initialIndex: index),
      ),
    );
  }

  Future<void> _toggleLike() async {
    if (liked) {
      // 取消点赞：简单回到未点赞状态（如果有后端请求请在此处处理）
      setState(() => liked = false);
      // 可选：做一个缩小动画再还原
      // await _likeController.reverse();
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    final p = widget.post;
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8),
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          /// 头部信息
          /// 时间
          Text('10分钟前', style: const TextStyle(fontSize: 14, height: 1.45)),
          SizedBox(height: 2.5.r),

          /// 文字
          Text(p.text, style: const TextStyle(fontSize: 14, height: 1.45)),
          if (p.images.isNotEmpty) const SizedBox(height: 10),

          /// 图片区域
          if (p.images.isNotEmpty) _buildImagesGrid(p.images),

          // SizedBox(height: 5.r),

          /// 评论区
          // _buildCommentSection(p),
        ],
      ),
    );
  }

  Widget _buildCommentSection(Post p) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: const Color(0xFFF3F6FA),
        borderRadius: BorderRadius.circular(10),
      ),
      padding: const EdgeInsets.all(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              _avatarsStack(),
              const SizedBox(width: 8),
              Text(
                '+${(p.likes / 1000).toStringAsFixed(1)}k',
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              const Spacer(),
              GestureDetector(
                onTap: _toggleLike,
                child: ScaleTransition(
                  scale: _scaleAnim,
                  child: Image.asset(
                    width: 15.r,
                    height: 16.r,
                    AtiAssets.trendListIcon,
                    color: liked ? Colors.redAccent : Colors.grey[700],
                    package: 'ati_package',
                  ),
                ),
              ),
              const SizedBox(width: 6),
              Text(
                _formatCount(p.likes + (liked ? 1 : 0)),
                style: const TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.w500,
                ),
              ),

              SizedBox(width: 17.5.r),
              _iconText(Icons.mode_comment_outlined, '${p.commentsCount}'),
            ],
          ),
          const SizedBox(height: 8),
          ...displayComments.map(
            (c) => Padding(
              padding: const EdgeInsets.only(bottom: 6),
              child: Text(c, style: const TextStyle(fontSize: 13, height: 1.3)),
            ),
          ),
          if (!commentsExpanded)
            GestureDetector(
              onTap: _expandComments,
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child: loadingComments
                    ? const SizedBox(
                        height: 18,
                        width: 18,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Text(
                        '展开更多评论...',
                        style: TextStyle(color: Colors.blue),
                      ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _avatarsStack() {
    const size = 28.0;
    final avatars = List.generate(4, (i) => widget.post.avatar);
    return SizedBox(
      height: size,
      width: size + (avatars.length - 1) * (size * 0.6),
      child: Stack(
        children: avatars.asMap().entries.map((entry) {
          final idx = entry.key;
          final url = entry.value;
          return Positioned(
            left: idx * (size * 0.6),
            child: CircleAvatar(
              radius: size / 2,
              backgroundImage: CachedNetworkImageProvider(url),
            ),
          );
        }).toList(),
      ),
    );
  }

  String _formatCount(int n) {
    if (n >= 1000) return '${(n / 1000).toStringAsFixed(1)}k';
    return '$n';
  }

  Widget _iconText(IconData icon, String text) {
    return Row(
      children: [
        Image.asset(
          width: 16.r,
          height: 13.5.r,
          AtiAssets.trendCommentIcon,
          package: 'ati_package',
        ),
        const SizedBox(width: 6),
        Text(text, style: const TextStyle(fontSize: 13)),
      ],
    );
  }

  Widget _buildImagesGrid(List<String> imgs) {
    final count = imgs.length;
    final screenW = MediaQuery.of(context).size.width;
    final available = screenW - 24 - 28;
    final itemSize = (available - 16) / 3;

    if (count == 1) {
      return GestureDetector(
        onTap: () => _openGallery(0),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(10),
          child: CachedNetworkImage(
            imageUrl: imgs[0],
            width: double.infinity,
            fit: BoxFit.cover,
            height: itemSize * 1.2,
          ),
        ),
      );
    }

    return Wrap(
      spacing: 8,
      runSpacing: 8,
      children: imgs.asMap().entries.map((e) {
        final idx = e.key;
        final url = e.value;
        return GestureDetector(
          onTap: () => _openGallery(idx),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8),
            child: CachedNetworkImage(
              imageUrl: url,
              width: itemSize,
              height: itemSize,
              fit: BoxFit.cover,
            ),
          ),
        );
      }).toList(),
    );
  }
}
